<?php
include('header.php');

	$commentson = false;
	$edit = false;

	// Has there been posted a new comment
	if(isset($_POST['addpostcomment'])) {
		//We want to attach the new comment to the right post document
		$criteria = array('_id' => new MongoId($_POST['postid']));
		
		//We update the post document with the new comment
		$update = array(
			//The operator $addToSet adds the data to the array but only if the data is not already there
			'$addToSet' => array(
				'comments' => array(
					'name' => $_POST['comment_author'],
					'email' => $_POST['comment_email'],
					'upVotes' => 0,
					'downVotes' => 0,
					'comment_date' => time(),
					'comment' => $_POST['comment_content'],
				)
			)
		);
		
		$new_comment_start = timeit();		
		// Perform the update
		q('post')->update($criteria, $update);
		$new_comment_end = timeit();
		$new_comment_time = number_format($new_comment_end - $new_comment_start, 15);
		redirect_to('view.php?postid='.$_POST['postid'].'&status=success&querytime='.$new_comment_time.'&query=new_comment');
	}
	
	if(isset($_GET['edit']) && ($_GET['edit'] != '')) {
		// We change view from viewing the blog post to been able to edit it. We find the right post _id and set the variable $edit to true
		$filter = array('_id' => new MongoId($_GET['postid']));
		$post = q('post')->findOne($filter);
		$edit = true;
	}

	//If there has been any editions done and submitted, we update the post
	if(isset($_POST['editpost'])) {
		$array = array();
		// To make sure that the post title and content does not breaks the JSON formattation, we add the PHP function addslashes before assigning it to the array.
		$array['post_title'] = addslashes($_POST['post_title']);
		$array['post_content'] = addslashes($_POST['post_content']);
		$array['tags'] = explode(", ", $_POST['post_tags']);
		
		$id = new MongoId($_POST['postid']);
		
		$update_query_start = timeit();		
		// Use $set to set the field _id to value $array
		q('post')->update(array('_id' => $id), array('$set' => $array));
		$update_query_end = timeit();
		$update_query_time = number_format($update_query_end - $update_query_start, 15);			
		
		redirect_to('view.php?postid='.$_POST['postid'].'&status=success&msg=edited&querytime='.$update_query_time.'&query=edit_post');
	}
	
	// If the delete link is pushed
	if(isset($_GET['delete']) && ($_GET['delete'] != "")) {
		$id = array('_id' => new MongoId($_GET['delete']));
		
		// We uses two options for the deletion:
		// justOne ensures that at most only one document matching the criteria must be removed
		// The other options to use are Safe. Safe ensures that the PHP code must wait for a response -
		// from the database whether the removal was successfull or not before the rest of the PHP code continue 
		$ops = array('justOne' => true, 'safe' => true);
		
		$delete_post_start = timeit();
		q('post')->remove($id, $ops);
		$delete_post_end = timeit();
		$delete_post_time = number_format($delete_post_end - $delete_post_start, 15);	
		redirect_to('posts.php?postid='.$_GET['delete'].'&status=success&msg=deleted&querytime='.$delete_post_time.'&query=delete_post');
	}

	// Check if the view page has a postid in its query, so we know what post to find
	if(isset($_GET['postid'])) {
		if(isset($_GET['p'])) {
			$commentpage = $_GET['p'];
		} else {
			$commentpage = 1;
		}
		
		// Get the post document id
		$postid = new MongoId($_GET['postid']);
		$limit = 5;
		$offset = ($commentpage -1) * $limit;
		$nextpage = ($commentpage +1);
		$prevpage = ($commentpage -1);
		
		$query = array('_id' => $postid);
		
		// Cast the value to array with (object)array
		// Use the $slice operator to retrive comments within the specific area from the pagination
		$condition = (object)array('comments' => array('$slice' => array($offset, $limit)));
		
		$findOne_start = timeit();		
		
		// Only retrieve at most one post document with findOne condition.
		$document = q('post')->findOne($query, $condition);
		$findOne_end = timeit();
		$findOne_time = number_format($findOne_end - $findOne_start, 15);		

		// use the DBRef to get the author of the post
		$ref = q()->getDBRef($document['author']);
		$author = $ref['name'];
		$date = date('d. M - Y', $document['date']);
		$time = date('H:i:s', $document['date']);
		$post_title = $document['post_title'];
		
		$the_content = $document['post'];
?>

<div id="container">
	<div id="main">
		<div class="postwarps">
			<div class="posts">
				<?php
					if(isset($_GET['status']) && ($_GET['status'] == 'success') && (isset($_GET['msg']) && ($_GET['msg'] == 'edited'))) {
						echo '<h1 style="color: red;">The post has been edited</h1>';
					}
				?>
				<?php if($edit) { ?>
					<form id="editpostform" name="editpost" action="view.php" method="post" enctype="multipart/form-data">
					<input type="hidden" value="<?php echo $postid; ?>" name="postid" />
				<?php }?>
				<div class="post_title" id="48">
					<?php
						if($edit) {
							echo '<input type="text" name="post_title" value="'. $post_title .'">';
						} else {
							echo $post_title;
						}
					?>
				</div>

				<div class="thumbnail" >
					<div class="postthumb"> 
						<img src="images/blogimages/blogimg_01.jpg" alt="<?php echo $post_title; ?>" title="<?php echo $post_title; ?>" width="630" height="300" border="0px"/></a> 
					</div>
				</div>
				<div class="postmetass">
					<div class="postmeta1">
						<span>Posted by :</span>&nbsp;<?php echo $author; ?>
					</div>
					<div class="postmeta2">
						<span>On :</span>&nbsp;<?php echo $date; ?>
					</div>
					<div class="postmeta3">
						<span>at :</span>&nbsp;<?php echo $time; ?>
					</div>
				</div>
				<div class="postconts">
					<?php
						if($edit) {
							echo '<textarea rows="8" cols="60" name="post_content" id="customTextarea">'.nl2br($the_content).'</textarea>';
						} else {
							echo nl2br($the_content);
						}
					?>
				</div>

				<div class="postmetass">
					<div class="postmetas5">
						<span>tags :</span>&nbsp; 
							<?php
								if($edit) {
									echo '<input type="text" name="post_tags" value="'. implode(", ", $document['tags']).'">';
								} else {
									echo implode(", ", $document['tags']);
								}
							?>
					</div>
				</div>
				<?php if($edit) { ?>
					<input type="image" src="images/submit2.png" class="submit" value="Submit" name="editpost"/>
					</form>
				<?php } ?>
			</div>
		</div>
<?php
 
	if(isset($document['comments'])) {
		$commentson = true;
			// To sort the comments by the date, the homemade function correctSort is applied
		$commentOrdered = correctSort($document['comments'],"comment_date");
		
		// Only show the comment field if there is a least one comment
		if($commentson) {
			
			// Perform a count on the comments to create paging
			$doc = q('post')->findOne($query);
			
			//Count the total comments
			$count = count($doc['comments']);
?>
		<div class="navigationt"></div>
		<div class="commentsf"> 
			<div id="comments">
				<div id="comments-list" class="comments">
					<h3><span><?php echo $count; ?></span> Comment(s)</h3>
					<?php
					if(isset($_GET['status']) && ($_GET['status'] == 'success')) {
						echo '<h1>Thank you! Your comment has been added</h1>';
					}
					
					//Iterate over each comment found in $document array
					foreach($commentOrdered as $comment) {
					?>
						<ol>
							<li id="comment-68" class="comment c c-y2012 c-m04 c-d24 c-h21 alt depth-1">
								<div class="comment-author vcard">
									<img alt='' src='images/blogimages/default_author_img.png' class='photo avatar avatar-80 photo' height='80' width='80' /> 
									<span class="fn n"><a href='http://www.google.com' rel='external nofollow' class='url url'><?php echo $comment['name']; ?></a></span>
								</div>
								<div class="comment-meta">
									<?php echo date('d. M - Y H:i:s', $comment['comment_date']); ?>
								</div>
								
								<div class="comment-content">
									<p><?php echo $comment['comment']; ?></p>
								</div>
							</li>
						</ol>
					<?php
					}
					?>

	<div class="navigationt">
		<div class='wp-pagenavi'>
			<?php
			// Add links for paging the comments
			if($commentpage > 1) {
				echo '<span class="pages"><a href="?postid='.$postid.'&p='.$prevpage.'">« Previous Page</a></span>';
				if($commentpage * $limit < $count) {
					echo '<a href="?postid='.$postid.'&p='.$nextpage.'">Next Page</a>';
					echo '<span class="pages"><a href="?postid='.$postid.'&p='.$nextpage.'">Next Page »</a></span>';
				}
			} else {
				if($commentpage * $limit < $count) {
					echo '<span class="pages"><a href="?postid='.$postid.'&p='.$nextpage.'">Next Page »</a></span>';
				}			
			}
			?>
		</div>
	</div>
	<div class="cleardiv"></div>
				</div>
<?php } ?>
				<div id="respond">
    				<h3>Post a Comment</h3>
					<div class="formcontainer">	
						<form id="commentform" name="postcomment" action="view.php" method="post" enctype="multipart/form-data">
							<input type="hidden" value="<?php echo $postid; ?>" name="postid" />
							<div class="commsec">
								<div id="form-section-author" class="form-section">
									<div class="form-label"><label for="author">Name</label> <span class="required">*</span></div>
									<div class="form-input"><input id="author" name="comment_author" type="text" value="" size="30" maxlength="20" tabindex="3" /></div>
								</div>

								<div id="form-section-email" class="form-section">
									<div class="form-label"><label for="email">Email</label> <span class="required">*</span></div>
									<div class="form-input"><input id="email" name="comment_email" type="text" value="" size="30" maxlength="50" tabindex="4" /></div>
								</div>
							</div>

                            <div id="form-section-comment" class="form-section">
    							<div class="form-label"><label for="comment">Comment</label></div>
    							<div class="form-textarea"><textarea id="comment" name="comment_content" cols="45" rows="8" tabindex="6"></textarea></div>
                            </div>
							
							<div class="form-submit"><input id="submit" name="addpostcomment" type="image" src="images/submit2.png" value="Post Comment" tabindex="7" /></div>
						</form>
					</div>
				</div>
			</div>
		</div>
<?php }
		}
 ?>
		<div class="cleardiv"></div>
	</div>
	<div class="sidebar">
		<div id="search_main" class="block">
			<form method="post" name="search" action="posts.php" enctype="multipart/form-data">
				<div>
					<input type="text" class="field" name="search" id="search" value="Search post content ..." onfocus="if (this.value == 'Search post content ...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search post content ...';}"/>
					<input type="image" src="images/sbtn.png" class="submit" name="submit"/>
				</div>
			</form>
		</div>
		
		<div class="widget">
			<div class="widgettitle">
				Navigation
			</div>
			<div class="widgetconten">
				<p><a href="posts.php">View all posts</a></p>
			</div>
		</div>		
		
		<div class="widget">
			<div class="widgettitle">
				Admin section
			</div>
			<div class="widgetconten">
				<p><a href="?postid=<?php echo $postid; ?>&edit=1">Edit this post</a></p>
				<p><a href="?delete=<?php echo $postid; ?>">Delete this post</a></p>
				<p><a href="add.php">Add new post</a></p>
				<p><a href="tests.php">Run Tests</a></p>
				<p><a href="indexcontrol.php?add=1">Add indexes</a></p>
				<p><a href="indexcontrol.php?delete=all">Delete all indexes</a></p>
			</div>
		</div>

		<div class="widget">
			<div class="widgettitle">
				MongoDB Query Information
			</div>
			<div class="widgetconten">
				<h3>Information</h3>
				<h3>Query time</h3>
				<?php
					if(isset($_GET['query']) && ($_GET['query'] != '')) {
						if($_GET['query'] == 'new_comment') {
							echo '<p>It took <span>' . $_GET['querytime'] . '</span> seconds to add new comment</p>';
						} elseif($_GET['query'] == 'edit_post') {
							echo '<p>It took <span>' . $_GET['querytime'] . '</span> seconds to update the post</p>';
						}
					}elseif(isset($findOne_time) && ($findOne_time != '')) {
						echo '<p>It took <span>' . $findOne_time . '</span> seconds to show the post</p>';
						
					}
				?>
				
			</div>
		</div>

	</div>
</div>

<?php
	include('footer.php');
?>